package com.shengsheng.expschedule.infrastructure.apigateway.filter;

import com.google.gson.JsonObject;
import com.shengsheng.expschedule.base.util.JwtInfo;
import com.shengsheng.expschedule.base.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author yuan
 * @date 2021/09/28
 */
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();

        // 校验访问 admin 接口用户必须登录
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        if (antPathMatcher.match("/admin/**/**", path)) {
            List<String> tokenList = request.getHeaders().get("token");
            // 没有token
            if (null == tokenList) {
                ServerHttpResponse response = exchange.getResponse();
                return AuthOut(response);
            }

            // token校验失败
            boolean isCheck = JwtUtils.checkJwtTToken(tokenList.get(0));
            if (!isCheck) {
                ServerHttpResponse response = exchange.getResponse();
                return AuthOut(response);
            }

            // 拿到 redis 中 用户名对应的 token 的值,检测用户的 token 是否已经被注销
            JwtInfo jwtInfo = JwtUtils.getJwtInfoByJwtToken(tokenList.get(0));
            String token = (String) redisTemplate.opsForValue().get(jwtInfo.getTeacherId());
            // redis 数据已清空
            if (StringUtils.isEmpty(token)) {
                ServerHttpResponse response = exchange.getResponse();
                return AuthOut(response);
            }
        }


        // 放行
        return chain.filter(exchange);
    }

    // 定义当前过滤器的优先级，值越小，优先级越高
    @Override
    public int getOrder() {
        return 0;
    }

    private Mono<Void> AuthOut(ServerHttpResponse response) {

        JsonObject message = new JsonObject();
        message.addProperty("success", false);
        message.addProperty("code", 22000);
        message.addProperty("data", "");
        message.addProperty("message", "鉴权失败，请登录");
        byte[] bytes = message.toString().getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bytes);
        // 指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        // 输出http响应
        return response.writeWith(Mono.just(buffer));
    }

    private Mono<Void> TokenErrorOut(ServerHttpResponse response) {

        JsonObject message = new JsonObject();
        message.addProperty("success", false);
        message.addProperty("code", 21004);
        message.addProperty("data", "");
        message.addProperty("message", "token 失效，请联系管理员重新获取链接");
        byte[] bytes = message.toString().getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bytes);
        // 指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        // 输出http响应
        return response.writeWith(Mono.just(buffer));
    }
}
